# /usr/bin/env python3.6
# -*- encoding: utf-8 -*-
"""
@File    : cinema_movie_api.py
@Time    : 2020/2/8 0008 10:30
@Author  : zhangbing
@Email   : 18829172841@163.com
@Software: PyCharm
"""
from flask import g
from flask_restful import reqparse, Resource, abort, fields, marshal

from App.apis.api_constant import HTTP_OK
from App.apis.cinema_admin.utils import login_cinema_required
from App.models.cinema_admin.cinema_movie_model import CinemaMovie
from App.models.common.movie_model import Movie

'''
此接口主要用于处理购买电影的问题，此电影是在影院用户的名下的
'''

parse = reqparse.RequestParser()
parse.add_argument("movie_id", type=int, required=True, help="Plase  input movie")

movie_cinema_fields = {
    "showname": fields.String,
    "shownameen": fields.String,
    "director": fields.String,
    "leadingRole": fields.String,
    "type": fields.String,
    "country": fields.String,
    "language": fields.String,
    "duraction": fields.String,
    "screeningmodel": fields.String,
    "openday": fields.DateTime,
    "backgroundpicture": fields.String,
}

movie_cinema_singal_fields = {
    "msg": fields.String,
    "status": fields.Integer,
    "data": fields.List(fields.Nested(movie_cinema_fields))
}


class CinemaMoviesResource(Resource):
    @login_cinema_required
    def get(self):
        user_id = g.user.id  # 获取此用户下的所有电影

        cinema_movies = CinemaMovie.query.filter(CinemaMovie.c_cinema_id == user_id).all()
        movies = []
        for cinema_movie in cinema_movies:
            movies.append(Movie.query.get(cinema_movie.c_movie_id))

        data = {
            "msg": "ok",
            "status": HTTP_OK,
            "data": movies
        }
        return marshal(data, movie_cinema_singal_fields)

    @login_cinema_required
    def post(self):
        user_id = g.user.id
        args = parse.parse_args()

        movie_id = args.get("movie_id")
        cinema_movies = CinemaMovie.query.filter(CinemaMovie.c_cinema_id == user_id).filter(
            CinemaMovie.c_movie_id == movie_id).all()
        if cinema_movies:
            abort(400, msg="此电影已经购买，不需要重复购买")

        cinema_movie = CinemaMovie()
        cinema_movie.c_movie_id = movie_id
        cinema_movie.c_cinema_id = user_id

        if not cinema_movie.save():
            abort(400, msg="影片购买失败！！")
        movie = Movie.query.get(movie_id)
        data = {
            "msg": "购买成功！！",
            "status": HTTP_OK,
            "data": marshal(movie, movie_cinema_fields)
        }
        return data


if __name__ == "__main__":
    pass
